<template>
  <div>
    <p class="text-center text-white bg-primary" style="padding: 10px">
      购物车
    </p>
    <div v-if="carts.length">
      <div
        class="media border border-light"
        v-for="(item, index) in carts"
        :key="item.id"
        style="margin: 10px"
      >
        <img
          :src="$imageUrl + item.goods.thumbnail"
          class="align-self-top mr-3"
          style="width: 100px"
        />
        <div class="media-body">
          {{ item.goods.name }}<br />
          单价：{{ item.goods.price }} &emsp;金额：{{
            item.num * item.goods.price
          }}<br />
          <button @click="countReduce(index)">-</button>
          <lable @change="updateNum(index)" v-model="item.num">{{
            item.num
          }}</lable>
          <button @click="countAdd(index)">+</button>
          <a
            @click="Remove(index)"
            class="float-right text-primary"
            style="margin-right: 30px"
            >移除</a
          >
        </div>
      </div>
      <h6 class="float-right" style="margin-right: 30px">
        总价：¥{{ totalPrice }}
      </h6>
      <br /><br />
      <div class="text-center">
        <router-link to="/Articles" class="btn btn-primary">返回首页</router-link>
         
        <router-link to="/AddressEdit" class="btn btn-primary">结算</router-link>
     
      </div>
      
    </div>
    <div v-else>购物车为空</div>
  </div>
</template>

<script>
export default {
  name: "ShoppingTrolley",
  data() {
    return {
      carts: [],
    };
  },
  methods: {
    countReduce(index) {
      if (this.carts[index].num === 1) return;
      this.carts[index].num--;
      this.updateNum(index);
    },
    countAdd(index) {
      this.carts[index].num++;
      this.updateNum(index);
    },
    updateNum(index) {
      this.$axios
        .put("cart", this.carts[index])
        .then((response) => {
          console.log(response);
        })
        .catch((error) => console.log(error)); // 请求失败处理
    },
    Remove(index) {
      this.$axios
        .delete("cart/" + this.carts[index].goodsid)
        .then((response) => {
          // console.log(response.data);
          this.carts.splice(index, 1); //从下标i开始删除1个元素：删除下标为i的元素
        })
        .catch((error) => console.log(error)); // 请求失败处理
    },
  },

  computed: {
    totalPrice() {
      var total = 0;
      for (var i = 0, len = this.carts.length; i < len; i++) {
        total += this.carts[i].goods.price * this.carts[i].num;
      }
      return total.toString();
    },
  },
  mounted() {
    //发送get请求
    this.$axios
      .get("cart")
      .then((response) => {
        //  console.log(response);
        this.carts = response.data.data;
      })
      .catch((error) => console.log(error)); // 请求失败处理
  },
};
</script>